﻿using DAL;
using Microsoft.Extensions.Logging;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    public class MeditionBLL
    {
        /// <summary>
        /// 依赖注入BaseDAL
        /// </summary>
        BaseDAL<MeditionModel> dal;
        BaseDAL<WardModel> warddal;
        ILogger<MeditionBLL> logger;

        public MeditionBLL(BaseDAL<MeditionModel> dal, BaseDAL<WardModel> warddal, ILogger<MeditionBLL> logger)
        {
            this.dal = dal;
            this.warddal = warddal;
            this.logger = logger;
        }



        /// <summary>
        /// 显示用药列表
        /// </summary>
        /// <param name="totalCount">总条数</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="doctorName">医生姓名</param>
        /// <param name="wardName">科室</param>
        /// <returns>返回受影响行数</returns>
        public IQueryable<MeditionModel> ShowMedition(out int totalCount,out int totalPage,int pageIndex=1,int pageSize=2,string? doctorName = "",string? wardName = "")
        {
            try
            {
                //1、未删除的数据
                var list = dal.Query().Where(x => x.IsDeleted == false);
                //2、根据条件查询
                if (!string.IsNullOrEmpty(doctorName)) 
                {
                    list=list.Where(x=>x.DoctorName.Contains(doctorName));
                }
                if (!string.IsNullOrEmpty(wardName)) 
                {
                    list=list.Where(x=>x.WardName==wardName);
                }
                //3、分页
                totalCount = list.Count();
                totalPage=(int)Math.Ceiling(totalCount*1.0/pageSize);
                list=list.OrderBy(x=>x.WardName).Skip((pageIndex-1)*pageSize).Take(pageSize);
                //4、返回集合
                logger.LogInformation($"{DateTime.Now}显示用药列表成功");
                return list;
            }
            catch (Exception ex)
            {
                logger.LogError("获取用药列表失败",ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 绑定下拉科室
        /// </summary>
        /// <returns>返回受影响行数</returns>
        public IQueryable<WardModel> GetWard()
        {
            try
            {
                logger.LogInformation($"{DateTime.Now}获取科室列表成功");
                return warddal.Query();
            }
            catch (Exception ex)
            {
                logger.LogError("获取科室列表失败", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 删除某条用药数据
        /// </summary>
        /// <param name="id">查询ID</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> DelMedition(int id)
        {
            try
            {
                //1、根据ID查询
                var list=await dal.Getasync(x=>x.MId==id);
                //2、修改Isdeleted的值
                list.IsDeleted=true;
                //3、更新数据库
                logger.LogInformation($"{DateTime.Now}删除成功");
                return await dal.Updasync(list);
            }
            catch (Exception ex)
            {
                logger.LogError("获取科室列表失败", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 修改状态为已完成
        /// </summary>
        /// <param name="ids">ID数组</param>
        /// <returns>受影响返回的行数</returns>
        public async Task<int> UpdState(string ids)
        {
            try
            {
                //1、将字符串转化成数组
                var idsArr = ids.Split(',');
                var res = 0;

                //2、循环
                foreach(string id in idsArr)
                {
                    //根据ID查询
                    var list=await dal.Getasync(x=>x.MId==Convert.ToInt32(id));
                    //修改状态的值
                    list.UseState = 0;
                    //遍历，更新数据库
                    res += await dal.Updasync(list);
                }
                //3、返回数组
                logger.LogInformation($"{DateTime.Now}修改状态成功");
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError("修改状态失败", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 反填用药
        /// </summary>
        /// <param name="id">查询ID</param>
        /// <returns>返回受影响行数</returns>
        public IQueryable<MeditionModel> GetMedition(int id)
        {
            try
            {
                logger.LogInformation($"{DateTime.Now}反填成功");
                return dal.Query().Where(x => x.MId == id);
            }
            catch (Exception ex)
            {
                logger.LogError("反填失败", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 修改用药
        /// </summary>
        /// <param name="m">用药表实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> Updasync(MeditionModel m)
        {
            try
            {
                //1、药品名称不能重复
                var list=await dal.Getasync(x=>x.Mname==m.Mname && x.MId!=m.MId && x.IsDeleted==false);
                if (list != null)
                {
                    return -1;
                }
                //2、修改
                logger.LogInformation($"{DateTime.Now}修改成功");
                return await dal.Updasync(m);
            }
            catch (Exception ex)
            {
                logger.LogError("修改失败", ex.Message);
                throw;
            }
        }
    }
}
